const { User } = require("../db/model/index");
const { formatUser } = require("./_format");

/**
 * 获取用户信息
 * @param {string} userName 用户名
 * @param {string} password 密码
 */
async function getUserInfo(userName, password) {
  //条件
  const whereOpt = {
    userName,
  };
  if (password) {
    Object.assign(whereOpt, { password });
  }
  //查询
  const result = await User.findOne({
    attributes: ["id", "userName", "nickName", "picture", "city"],
    where: whereOpt,
  });

  if (result === null) {
    return null;
  }
  return formatUser(result.dataValues);
}

/**
 * 创建用户
 * @param {string} userName
 * @param {string} password 密码
 * @param {number} gender 性别 (1 男， 2 女， 3 保密)
 * @param {string} nickName 昵称
 */
async function createUser({ userName, password, gender = 3, nickName }) {
  const result = await User.create({
    userName,
    password,
    gender,
    nickName: nickName || userName,
  });
  return result.dataValues;
}

/**
 * 删除用户
 * @param {string} userName 用户名
 */
async function deleteUser(userName) {
  const result = await User.destroy({
    where: {
      userName,
    },
  });
  return result > 0;
}

async function updateUser(
  { newNickName, newPassword, newCity, newPicture },
  { userName, password }
) {
  const updateData = {};
  if (newNickName) {
    updateData.nickName = newNickName;
  }
  if (newPassword) {
    updateData.password = newPassword;
  }
  if (newCity) {
    updateData.city = newCity;
  }
  if (newPicture) {
    updateData.picture = newPicture;
  }
  const whereData = {
    userName,
  };
  if (password) {
    whereData.password = password;
  }
  const res = await User.update(updateData, {
    where: whereData,
  });
  return res[0] > 0;
}

module.exports = {
  getUserInfo,
  createUser,
  deleteUser,
  updateUser,
};
